const Service = require('egg').Service

class ShareService extends Service {

  async creatShare(params) {
    const ctx = this.ctx
    return new Promise(async (resolve, reject) => {

      try {
        const newTempLate = await ctx.model.Template.findOneAndUpdate({ _id: params.templateId }, {
          $inc: {
            shareCounts: 1
          }
        }, { new: true });

        let share;
        if (params.shareId) {
          share = await ctx.model.Share.findOne({ _id: params.shareId });
        }

        const data = {
          type: 0, // 分享形式
          target: newTempLate.target._id, // 目标地址
          author: newTempLate.author._id, // 分享者ID
          templateId: params.templateId
        }
        if (ctx.state && ctx.state.user) {
          data.type = 1
          data.creator = ctx.state.user.id
        }
        
        if (share) {
          data.type = 2
          data.from = share.creator // 上级分享者ID
        }
        const newShare = ctx.model.Share(data).save()
        if (newShare && newTempLate) {
          resolve(newShare)
        }
      } catch (err) {
        reject(err);
      }
    })
  }
}

module.exports = ShareService;
